
cap program drop PlotCoeff_detrend
program define PlotCoeff_detrend
syntax,  NAME(string) XLINE(real) XLINE2(real) [YLABEL(string)] [XLABEL(string)] VRS(string) [TITLE(string)] [YTI(string)] [XTI(string)] 
*syntax, NAME(string) XLINE(real) [YLABEL(string)] [XLABEL(string)] VRS(string) [TITLE(string)] [YTI(string)] [OVERRIDE]

	mat b = e(b)
	mat s = e(V)

	foreach vr in `: colnames b' {
		
		local iter = `iter'+1
		
		mat x = b[1,"`vr'"]
		local beta = x[1,1]

		mat y = s[`iter',"`vr'"]
		local se = sqrt(y[1,1])

		local obs`iter' "`: colnames x'|`beta'|`se'"

		macro drop _beta _se
		mat drop x y
	}
	
	
	preserve

		clear
		qui set obs `iter'
		qui gen ind=""
		forval vl = 1/`iter' {
			qui replace ind="`obs`vl''" in `vl'
			macro drop _obs`vl'
		}
		macro drop _iter
		
		qui split ind, parse("|")
		qui keep if regexm(ind1,"`vrs'")==1
		
		qui gen beta=ind2
		qui gen se=ind3
		
		* Set omitted variables to missing
		qui replace beta="" if regexm(ind1,"o.`vrs'")
		qui replace se="" if regexm(ind1,"o.vrs")
		*if "`override'"=="" qui replace beta="" if regexm(ind1,"o.`vrs'")
		*if "`override'"=="" qui replace se="" if regexm(ind1,"o.`vrs'")
		
		* Drop constant
		qui drop if ind1=="_cons"
		
		* Generate etime
		qui split ind1, parse("_") 
		replace ind12=subinstr(ind12,"m","-",.)
		qui destring ind12, replace
		confirm numeric var ind12
		qui gen etime=ind12

		keep beta se etime

		qui destring _all, replace
		confirm numeric var etime beta se
						
		gen ind=1
		qui tsset ind etime
		qui tsfill
		*qui replace beta=0 if beta==. & etime==-1
		drop ind
		
		* Get pretrend ----------------------------- *
		reg beta etime if inrange(etime, -12,-1)
		predict beta2
		replace beta = beta - beta2
		drop beta2
		* ------------------------------------------ *

		qui replace beta=0 if beta==. & etime==-1
		qui gen low=beta-(1.96*se)
		qui gen hi=beta+(1.96*se)
		
		if "`ylabel'"!="" local ylabel `"ylabel(`ylabel')"'
		if "`xlabel'"!="" local xlabel `"xlabel(`xlabel')"'
		if "`title'"!=""  local title  "`title'"
		
		if "`yti'"!=""   local yti `"`yti'"'
					else local yti "Estimated effect on log hourly wages"
		if "`xti'"!=""   local xti `"`xti'"'
					else local xti "Event time in months"

		#d 
			twoway rcap hi low etime || connected beta etime,
			
			yline(0, lcolor(black) lw(vthin))
			xline(`xline', lcolor(red) lw(vthin)) 
			xline(`xline2', lcolor(black) lw(vthin)) 	
			
			`ylabel' `xlabel' 
			
			title("`title'")
			xti("`xti'") 
			yti("`yti'", margin(0 4 0 0))
			
			ylabel(, glc(gs14) glw(vthin))
			
			legend(off) name(`name', replace)
			
			graphregion(color(white) margin(small))
		;
		#d cr
		
	restore

	mat drop b s
	
end

